<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索框和按钮区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <div style="margin-top: 15px">
            <el-input
              placeholder="请输入用户名称"
              v-model="queryInfo.query"
              clearable
              @clear="getUserList"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUserList"
              ></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            class="adduser_button"
            @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userlist" style="width: 100%" border stripe>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUser(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        :before-close="handleClose"
        @close="addDialogClose"
      >
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="ruleFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息对话框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <el-form
          ref="editFormRef"
          :model="editForm"
          label-width="80px"
          :rules="editFormRules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClose"
    >
      <div>
        <!-- 用户名称 -->
        <p>当前的用户：{{ userinfo.username }}</p>
        <!-- 用户角色 -->
        <p>当前的角色：{{ userinfo.role_name }}</p>
        <p>
          分配的新角色：
          <el-select v-model="roleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (regEmail.test(value)) {
        // 邮箱合法
        return cb()
      }
      cb(new Error('请输入合法的邮箱！'))
    }
    // 验证密码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
      if (regMobile.test(value)) {
        // 密码合法
        return cb()
      }
      cb(new Error('请输入合法的电话！'))
    }
    return {
      // 分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 被分配角色的用户信息
      userinfo: {},
      // 角色列表数据
      roleList: [],
      // 用户被分配的新角色id
      roleId: '',
      //  获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      editForm: {},
      // 添加表单对象
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''

      },
      // 添加表单用户规则对象
      addFormRules: {
        username: [{ required: true, message: '请输入用户名称', trigger: 'blur' },
        { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }],
        password: [{ required: true, message: '请输入用户密码', trigger: 'blur' },
        { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }],
        email: [{ required: true, message: '请输入用户邮箱', trigger: 'blur' },
        { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [{ required: true, message: '请输入用户电话', trigger: 'blur' },
        { validator: checkMobile, trigger: 'blur' }]
      },
      editFormRules: {
        mobile: [{ required: true, message: '请输入用户电话', trigger: 'blur' },
        { validator: checkMobile, trigger: 'blur' }],
        email: [{ required: true, message: '请输入用户邮箱', trigger: 'blur' },
        { validator: checkEmail, trigger: 'blur' }]
      }

    }
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo });
      console.log(res);
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    // 每页条数
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUserList()
    },
    // 当前页
    handleCurrentChange(val) {
      // console.log(val);
      this.queryInfo.pagenum = val;
      this.getUserList()
    },
    // 用户状态更改事件
    async userStateChange(userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`);
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.err('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
    },
    addDialogClose() {
      this.$refs.ruleFormRef.resetFields()
    },
    // 增加用户预验证
    addUser() {
      this.$refs.ruleFormRef.validate(async (volid) => {
        // console.log(volid);
        if (!volid) {
          return
        }
        // 预验证通过，发起添加用户请求
        const { data: res } = await this.$http.post("users", this.addForm);
        // console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }

        this.$message.success('增加用户成功!');
        this.addDialogVisible = false;
        this.getUserList();
      })
    },
    // 修改用户信息对话框事件
    async showEditDialog(id) {
      this.editDialogVisible = true;
      const { data: res } = await this.$http(`users/${id}`);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.editForm = res.data;
    },
    // 监听用户修改信息对话框取消事件

    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 监听修改用户信息对话框确定事件
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(this);
        if (!valid) return
        //  表单预验证通过

        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败！')
        }
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新列表数据
        this.getUserList()
        // 提示修改成功
        this.$message.success('更新用户信息成功！')
      })
    },
    // 为用户列表删除按钮监听点击事件
    async removeUser(id) {
      // console.log(id);
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmResult);
      if (confirmResult !== 'confirm') {
        return this.$message('已取消删除！')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.getUserList()
    },
    // 监听点击分配角色点击事件
    async setRole(userinfo) {
      console.log(userinfo);
      this.userinfo = userinfo
      // 获取角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.roleList = res.data
      console.log(this.roleList);
      this.setRoleDialogVisible = true
    },
    // 监听分配角色对话框确定事件
    async setUserRole() {
      if (!this.roleId)
        return this.$message.error('请选择一个角色！')
      const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`,
        { rid: this.roleId })
      if (res.meta.status !== 200)
        return this.$message.error('角色修改失败！')
      this.$message.success('更改用户角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false

    },
    // 分配用户新角色对话框关闭时
    setRoleDialogClose() {
      this.userinfo = {}
      this.roleId = ''
    }

  }
}
</script>
<style lang="less" scoped>
.adduser_button {
  margin-top: 15px;
}
</style>